﻿using System;
using BikeBouncer.BusinessLayer;
using BikeBouncer.BusinessLayer.Entities;
using BikeBouncer.BusinessLayer.Enums;
using Devv.Core.Utils;

namespace BikeBouncer.Site
{
	public partial class BoxSearch_aspx : BaseBoxPage
	{
		#region Page methods

		protected void Page_Load(object sender, EventArgs e)
		{
			SecurityManager.SearchCheckIP();

			Boolean timeLimit = DateTime.Now.AddMinutes(-1 * ConfigUtil.GetConfig("BikeBouncer.Search.TimeLimit", 5)) < SessionManager.SearchCountDate;

			if (timeLimit)
			{
				if (SessionManager.SearchCount > ConfigUtil.GetConfig("BikeBouncer.Search.MaxCount", 3))
				{
					AppendError(GetLocalResourceObject("Error_SearchCountLimit").ToString());
					return;
				}
			}
			else
			{
				SessionManager.SearchCount = 0;
			}

			SessionManager.SearchCount += 1;

			String serial = Request.QueryString["serial"];

			if (String.IsNullOrEmpty(serial))
			{
				PanItem.Visible = false;
			}
			else
			{
				SearchSerial(serial);
			}
		}

		#endregion

		#region Search

		private void SearchSerial(String serial)
		{
			Item item = new Item(DataAccess.Item_GetBySerial(serial));

			if (item.Id > 0)
			{
				Note note = new Note(DataAccess.Note_Get(item, item.StatusDate, 2));
				String status;

				if (item.Status == ItemStatus.Lost || item.Status == ItemStatus.Stolen)
				{
					status = GetLocalResourceObject("StatusStolen").ToString();
					status = status.Replace("#STATUS#", GetGlobalResourceObject("Messages", "Status" + item.Status).ToString());
					status = status.Replace("#DATE#", item.StatusDate.ToShortDateString());

					LblStatus.CssClass = "Error";
				}
				else if (item.Status == ItemStatus.Spotted)
				{
					status = GetLocalResourceObject("StatusSpotted").ToString();

					LblStatus.CssClass = "Warning";
				}
				else
				{
					status = GetLocalResourceObject("StatusRegistered").ToString();

					LblStatus.CssClass = "Ok";

					PanReport.Visible = false;
				}

				LblLocation.Text = LblLocation.Text.Replace("#SERIAL#", item.Serial);

				if (note.Address.Id > 0)
				{
					LblLocation.Text = LblLocation.Text.Replace("#LOCATION#", note.Address.City.ToString(", "));
				}
				else
				{
					LblLocation.Text = LblLocation.Text.Replace("#LOCATION#", Settings.DefaultCountry);
				}

				ImgItem.ImageUrl = item.PictureUrl;
				LblStatus.Text = status;

				LinkReport.NavigateUrl = "/BoxAddNote.aspx?refid=" + note.Id;

				PanNoResults.Visible = false;
			}
			else
			{
				PanItem.Visible = false;
			}
		}

		#endregion
	}
}